//
//  IndexViewController.swift
//  fsApp
//
//  Created by zguang on 17/7/26.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import Alamofire
let SCREEN_WIDTH = UIScreen.main.bounds.size.width


class IndexViewController: UIViewController, SliderGalleryControllerDelegate,UITableViewDelegate,UITableViewDataSource{
    
    var sliderGallery:SliderGalleryController!
    var tableview = UITableView()
    //获取屏幕宽度
    let screenWidth =  SCREEN_WIDTH
    var TitledataSource = [String]()
    var detail = [String]()
    var cover = [String]()
    var turnImageArray = [String]()
    var turnVideo_url = [String]()
    var turnVidep_title = [String]()
    var turnVideo_ID = [String]()
    var detailContent = [String]()
    
    
    override func viewWillAppear(_ animated: Bool) {
        self.tabBarController?.tabBar.isHidden = false
        let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        //标题颜色
        self.navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
        self.navigationItem.title = "大汉易经书院智慧生活"
        self.navigationController?.navigationBar.isTranslucent = false
        //  self.navigationController?.navigationBar.backgroundColor = naviColor
        self.navigationController?.navigationBar.barTintColor = naviColor

    }
    

    

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //  print(String(describing: idfa))
        

        
        self.tabBarController?.tabBar.isHidden = false
        self.edgesForExtendedLayout = UIRectEdge(rawValue:0)
        getTurn()
        Alarequest()
        getVersion()
        initTV()
        //self.initSliderView()
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - tableview协议
    
    func initTV (){
        tableview.frame = CGRect(x:0,y:0,width:SCREEN_WIDTH,height:SCREEN_HEIGHT)
        tableview.delegate = self
        tableview.dataSource = self
       // tableview.backgroundColor = UIColor.blue
       // view.backgroundColor = UIColor.red
       // self.view.addSubview(tableview)
         self.view.addSubview(tableview)
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return TitledataSource.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return height(292)
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = IndexTableViewCell(style:.default,reuseIdentifier:"cell")
        cell.Headimage.imageFromURL(self.cover[indexPath.row], placeholder: #imageLiteral(resourceName: "test"))
       // print(self.TitledataSource[indexPath.row])
        
        cell.title.text = self.TitledataSource[indexPath.row]
        cell.title.sizeToFit()
        cell.detail.text = self.detail[indexPath.row]
        
        return cell
        
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
        //self.navigationItem.backBarButtonItem?.image = #imageLiteral(resourceName: "return")
        let vc = textDetailViewController(title:self.TitledataSource[indexPath.row],content:detailContent[indexPath.row],index:indexPath.row)
        self.navigationController?.pushViewController(vc, animated: true)
        
    
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return  height(407) + height(19+89)
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x:0,y:0,width:SCREEN_WIDTH,height:getHeight(407+89+19)))
        let viewLine = UIView(frame: CGRect(x:0,y:getHeight(407),width:SCREEN_WIDTH,height:getHeight(19)))
        viewLine.backgroundColor = UIColor.init(red: 241/255, green: 242/255, blue: 242/255, alpha: 242/255)
        let viewHead = UIView(frame: CGRect(x:0,y:getHeight(407+19),width:SCREEN_WIDTH,height:getHeight(89)))

        let imageBook = UIImageView()
        imageBook.frame = CGRect(x:width(20),y:height(18),width:width(50),height:height(50))
        imageBook.image = #imageLiteral(resourceName: "书院简介")
        let label = UILabel()
        label.frame = CGRect(x:width(74),y:height(29),width:width(150),height:height(32))
        label.text = "书院简介"
        label.font = UIFont.systemFont(ofSize: height(32))
        viewHead.addSubview(imageBook)
        viewHead.addSubview(label)
        viewHead.backgroundColor = UIColor.white
         if sliderGallery != nil{
        view.addSubview(sliderGallery.view)
        }
        view.addSubview(viewHead)
        view.addSubview(viewLine)
        return view
    }

    
    
    
    
    // MARK: - 轮播图协议
    //图片轮播组件协议方法：获取内部scrollView尺寸
    
    func initSliderView(){
        //初始化图片轮播组件
        sliderGallery = SliderGalleryController()
        sliderGallery.delegate = self
        sliderGallery.view.frame = CGRect(x: 0, y: 0, width: screenWidth,
                                          height: height(407));
        sliderGallery.view.backgroundColor = UIColor.white
        //将图片轮播组件添加到当前视图
        self.addChildViewController(sliderGallery)
        
       //self.view.addSubview(sliderGallery.view)
        
        //添加组件的点击事件
        let tap = UITapGestureRecognizer(target: self,
                                         action: #selector(handleTapAction(_:)))
        sliderGallery.view.addGestureRecognizer(tap)
        

    }
    
    
    
    func galleryScrollerViewSize() -> CGSize {
        return CGSize(width: screenWidth, height:height(407))
    }
    
    //图片轮播组件协议方法：获取数据集合
    func galleryDataSource() -> [String] {
        return self.turnImageArray
    }
    
    //点击事件响应
    func handleTapAction(_ tap:UITapGestureRecognizer)->Void{
        
        //获取图片索引值
        let index = sliderGallery.currentIndex
        //弹出索引信息
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
        self.present(VideoDetailViewController(self.turnVideo_url[index],self.turnVideo_ID[index]), animated: true, completion: nil)
        // self.hidesBottomBarWhenPushed = true
       //self.navigationController?.pushViewController(VideoDetailViewController(self.turnVideo_url[index],self.turnVideo_ID[index]), animated: true)
        self.hidesBottomBarWhenPushed = false
        let alertController = UIAlertController(title: "您点击的图片索引是：",
                                                message: "\(index)", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        //self.present(alertController, animated: true, completion: nil)
    }

    
    func Alarequest(){

        let url = "http://dahan-api.heiyou.net/index.php/home/index/getIntro"
        Alamofire.request( url, method: .post).responseJSON{ response in
            print("result=========================")
            if let sds = response.response{
            }else{
                print("网络异常")
            }
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
               // print(js)
                self.cover.append(js["result"][0]["cover"].string!)
                self.TitledataSource.append(js["result"][0]["title"].string!)
                self.detail.append(js["result"][0]["info"].string!)
                self.cover.append(js["result"][1]["cover"].string!)
                self.TitledataSource.append(js["result"][1]["title"].string!)
                self.detail.append(js["result"][1]["info"].string!)
                self.detailContent.append(js["result"][0]["content"].string!)
                self.detailContent.append(js["result"][1]["content"].string!)
                self.tableview.reloadData()
            }
        }
    }
    
    func getTurn (){
        
        let url = "http://dahan-api.heiyou.net/index.php/home/index/getturn"
        Alamofire.request( url, method: .post).responseJSON{ response in
            print("result=========================")
            if let sds = response.response{
            }else{
                print("网络异常")
            }
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
               // print(js)
                
                if js["status"] == 200{
                    if js["result"].count != 0{
                        for i in 0...js["result"].count-1{
                            self.turnImageArray.append(js["result"][i]["pic_src"].string!)
                            self.turnVideo_url.append(js["result"][i]["video_src"].string!)
                            self.turnVidep_title.append(js["result"][i]["name"].string!)
                            self.turnVideo_ID.append(js["result"][i]["id"].string!)
                        }
                        DispatchQueue.main.async {
                           self.tableview.reloadData()
                           self.initSliderView()
                        }
                    }
                
            }
        }

    }
    }
    
    
    func getVersion (){
        
        let url = "http://dahan-api.heiyou.net/index.php/home/index/getVersionforIOS"
        Alamofire.request( url, method: .post).responseJSON{ response in
            print("result=========================")
            if let sds = response.response{
            }else{
                print("网络异常")
            }
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
                
                if js["status"] == 200{
                    let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
                    
                    let newVersion = js["result"][0]["status"].string!
                    let newNum = js["result"][1]["version"].string!
                    print(currentVersion)
                    print(newNum)
                    if newVersion !=  "1" {
                        if newNum.compare(currentVersion) == ComparisonResult.orderedDescending {
                                                let Alert = UIAlertController(title:"发现新版本",message:"请及时更新到新版本",preferredStyle:.alert)
                                                let okAction = UIAlertAction(title:"更新",style:.default,handler:{ acton in
                                                    
                                                    let url = URL(string:"https://itunes.apple.com/cn/app/id1266534282?mt=8")
                                                    //"https://itunes.apple.com/cn/app/id1266534282?mt=8")
                                                    UIApplication.shared.openURL(url!)
                                                    print("ok")
                                                })
                                                let cancel = UIAlertAction(title:"取消",style:.cancel,handler:nil)
                                                Alert.addAction(okAction)
                                                Alert.addAction(cancel)
                                                self.present(Alert, animated: true, completion: nil)
                                               print("版本升级")
                    
                                            }else{
                                               print("无需升级")
                        
                                           }
                

                    }
                    
   
                    
                }
            }
            
        }
    }
    
    
    
      /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}



